package com.xpqh.ksg.common.utils;

/**
 * Snowflake 改进版 UID 生成器
 */
public class IdGenerator {
    // 每部分占用位数
    private final long nodeIdBits = 10L;
    private final long sequenceBits = 12L;

    // 最大值
    private final long maxSequence = ~(-1L << sequenceBits);

    // 节点ID偏移量
    private final long nodeIdShift = sequenceBits;
    private final long timestampLeftShift = sequenceBits + nodeIdBits;

    private long lastTimestamp = -1L;
    private long sequence = 0L;
    private final long nodeId;

    public IdGenerator(long nodeId) {
        this.nodeId = nodeId << sequenceBits;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & maxSequence;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        return (timestamp << timestampLeftShift)
               | nodeId
               | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    public static void main(String[] args) {
        IdGenerator idGenerator = new IdGenerator(1); // 节点ID为1
        for (int i = 0; i < 10; i++) {
            System.out.println(idGenerator.nextId());
        }
    }
}
